<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/6/1
 * Time: 上午10:33
 */

namespace app\api\controller;


use app\common\controller\ActionLogs;
use app\common\model\Agent;
use app\common\model\CardConsume;
use app\common\model\CardCzgive;
use app\common\model\CardGeneral;
use app\common\model\CardMember;
use app\common\model\CardRank;
use app\common\model\CardUserBonus;
use app\common\model\CardUserGet;
use app\common\model\CardUserRecLog;
use app\common\model\CardUserUpdate;
use app\common\model\DeviceMicro;
use app\common\model\LoginUsers;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\System;
use app\common\model\Tklog;
use app\common\model\WxOpen;
use think\Controller;
use Wechat\Wxobjopen;

class Pub extends Controller
{
    //获取相关联的商户号列表，
    public function getmidlist($type, $data)
    {

        $Merchant = new Merchant();
        switch ($type) {
            case "mid":
                $top_mid = $Merchant->where('id', $data)->value('top_mid');
                break;
            case "topmid":
                $top_mid = $data;
                break;
        }
        $midlist = $Merchant->where('top_mid', $top_mid)->field('id')->select();
        $mids = [];
        foreach ($midlist as $k => $v) {
            $mids[] = $v['id'];
        }
        return $mids;
    }

    //获取核销状态    0可用/1不可用
    public function consumestatu($card_id, $code)
    {
        $data = [
            'card_id' => $card_id,
            'code' => $code,
            'check_consume' => true
        ];
        $options = $this->options($data['card_id']);
        $wxObj = new Wxobjopen($options);
        $res = $wxObj->getCardState($data);

        if ($res['errcode'] == 0 && $res['errmsg'] == 'ok') {
            return '0';
        } else {
            return '1';
        }

    }

    protected function getorderid($sh, $type = "")
    {
        if (empty($type) || $type == "pay") {
            $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999) . rand(1, 9);
        } elseif ($type == "wsy") {
            $order = "H" . $sh . date('YmdHis') . rand(10000, 99999) . rand(1, 9);

        } else {
            $order = "C" . $sh . "-" . date('YmdHis') . rand(10000, 99999) . rand(1, 9);
        }
        return $order;
    }
    public function genbusorderid($sh){
        $order = "bus" . $sh . "-" . date('YmdHis') . rand(10000, 99999) . rand(1, 9);
        return $order;
    }

    public function options($card_id)
    {
        //  Session::set('openid', null);
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
        $System = new System();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $mid = $CardMember->where('card_id', $card_id)->value('mid');
        if ($mid) {
            $map['id'] = $mid;
        } else {
            $map['id'] = $CardGeneral->where('card_id', $card_id)->value('mid');
        }
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config =$System->where(array('id' => 1))->find();
        $users = $WxOpen->where($mab)->find();
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }
    //获取subopenid
    //merchantid   auth_code
    public function getsubopenid($param)
    {
        $map['id'] = $param['merchantid'];
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );
        $weObj = new Wxobjopen($options);
        //会员卡支付
        $appid = $WxOpen->where('id', $config['wx_open_id'])->value('authorizer_appid');
        $sparam['appid'] = $users['authorizer_appid'];
        $sparam['sub_appid'] = $appid;
        $sparam['mch_id'] = $agent['partnerid'];
        $sparam['sub_mch_id'] = $config['sub_mch_id'];
        $sparam['auth_code'] = $param['auth_code'];
        $getpenid = $weObj->get_open_id($sparam);
        if ($getpenid['return_code'] !== "FAIL" && $getpenid['result_code'] !== "FAIL") {
            $openid = $getpenid['sub_openid'];
        } else {
            $openid = '';
        }
        return $openid;
    }
    //等级折扣
    //merchantid auth_codel
    public function rankzk($param)
    {
        $cardinfo = $this->getcard($param);
        if ($cardinfo) {
            $cardmember = new CardMember();
            $cardus = $cardmember->where('card_id', $cardinfo['card_id'])->find();
            $dz = $cardus['is_dj_discount'];
            if ($dz == 1) {
                //有
                $subopenid = $this->getsubopenid($param);
                if (!empty($subopenid)) {
                    $openid = $subopenid;
                    $card_id = $cardinfo['card_id'];
                    $CardUserGet = new CardUserGet();
                    $userinfo = $CardUserGet->where(['card_id' => $card_id, 'openid' => $openid])->find();
                    $level = getlive($card_id, $userinfo['bonus']);
                    $CardRank = new CardRank();
                    $rankinfo = $CardRank->where(['card_id' => $card_id, 'live' => $level])->find();
                    if ($rankinfo['discount']) {
                        $res = $rankinfo['discount'] / 100;
                    } else {
                        $res = 1;
                    }
                } else {
                    $res = 1;
                }
            } else {
                $res = 1;
            }
        } else {
            $res = 1;
        }

        return $res;
    }
    //卡券折扣
    //merchantid
    public function getcard($param)
    {
        $subopenid = $this->getsubopenid($param);
        if (!empty($subopenid)) {
            if (!empty($subopenid)) {
                $openid = $subopenid;
                $CardUserGet = new CardUserGet();
                $mid = $this->getmidlist('mid', $param['merchantid']);
                $me['openid'] = $openid;
                $me['mid'] = array('in', $mid);
                $me['have'] = 1;
                $me['statu'] = 0;
                $me['fire'] = 1;
                $me['card_type'] = 'MEMBER_CARD';
                $cardinfo = $CardUserGet->where($me)->find();

            } else {
                $cardinfo = [];
            }
        } else {
            $cardinfo = "error";
        }
        return $cardinfo;
    }

    public function get_card_userinfo($mid, $openid)
    {
        $Merchant = new Merchant();
        $top_mid = $Merchant->where('id', $mid)->value('top_mid');
        $CardUserGet = new CardUserGet();
        $map = array(
            'top_mid' => $top_mid,
            'openid' => $openid,
            'have' => 1,
            'fire' => 1,
            'status' => 1,
            'statu' => 0,
            'card_type' => "MEMBER_CARD",
        );
        $carduserinfo = $CardUserGet->where($map)->find();
        return $carduserinfo;
    }

    //只舍不入
    public function format_price($price)
    {
        $price = (float)$price;//将数值转换为浮点数
        $str = explode(".", $price);//将字符串转换为数组
        if (isset($str[1])) {//判断是否存在小数点
            $str2 = strlen($str[1]);//获取小数点位数
            if ($str2 <= 2) {//当小数点位数小于等于2 原样输出
                $data = $price;
            } else {
                $str4 = substr($str[1], 0, 2);//取出小数点后两位的值
                $str5 = substr($str[1], 0, 1);//取出小数点后1位的值
                if ($str4 == "00") {//当小数点后2为未00时直接+1
                    $str3 = "01";
                } elseif ($str5 == "0") {//当小数点后1为为0时直接最后1位+1
                    if (substr($str[1], 1, 1) + 1 !== 10) {
                        $str3 = (string)$str5 . (substr($str[1], 1, 1) + 1);
                    } else {
                        $str3 = substr($str[1], 0, 1) + 1;
                    }
                } else {//不满足上述条件直接+1
                    $str3 = substr($str[1], 0, 2) + 1;
                }
                if ($str3 == 100) {//当金额为X.99X直接整数+1
                    $data = ($str[0] + 1);
                } else {
                    $data = $str[0] . '.' . $str3;
                }
            }
        } else {
            $data = $price;
        }
        return $data;
    }

    //折扣计算
    public function format_zkprice($price)
    {
        if ($price >= 0.01) {
            $price = (float)$price;//将数值转换为浮点数
            $str = explode(".", $price);//将字符串转换为数组
            if (isset($str[1])) {//判断是否存在小数点
                $str2 = strlen($str[1]);//获取小数点位数
                if ($str2 <= 2) {//当小数点位数小于等于2 原样输出
                    $data = $price;
                } else {
                    $str4 = substr($str[1], 0, 2);//取出小数点后两位的值
                    $str5 = substr($str[1], 0, 1);//取出小数点后1位的值
                    if ($str4 == "00") {//当小数点后2为未00时直接+1
                        $str3 = "01";
                    } elseif ($str5 == "0") {//当小数点后1为为0时直接最后1位+1
                        if (substr($str[1], 1, 1) + 1 !== 10) {
                            $str3 = (string)$str5 . (substr($str[1], 1, 1) + 1);
                        } else {
                            $str3 = substr($str[1], 0, 1) + 1;
                        }
                    } else {//不满足上述条件直接+1
                        $str3 = substr($str[1], 0, 2) + 1;
                    }
                    if ($str3 == 100) {//当金额为X.99X直接整数+1
                        $data = ($str[0] + 1);
                    } else {
                        $data = $str[0] . '.' . $str3;
                    }
                }
            } else {
                $data = $price;
            }
        } else {
            $data = 0;
        }
        return $data;
    }

//查询收银员是否属于该门店
    public function checkcashier($data)
    {
        $Cachier = new LoginUsers();
        $cachi = $Cachier->where(['username' => $data['device_id']])->find();
        $DeviceMicro = new DeviceMicro();
        $map['mid'] = array('in', $this->getmidlist('mid', $data['merchantid']));
        $map['device_code'] = $data['device_id'];
        $de = $DeviceMicro->where($map)->find();
        if ($cachi['level'] == 3001 || isset($de)) {
            return 0;
        } else {
            $mid = explode(',', $cachi['mid']);
            foreach ($mid as $v) {
                if ($v == $data['merchantid']) {
                    return 0;
                }
            }
        }
        return 1;
    }

    //支付完成后获取订单信息
    public function getorderinfo($orderid)
    {
        $map['orderid'] = $orderid;
        $Paylog = new Paylog();

        $payinfo = $Paylog->where($map)->find();
        if (!empty($payinfo['cashier'])) {
            $device_id = $payinfo['cashier'];

        } elseif (!empty($payinfo['d_cashier'])) {
            $device_id = $payinfo['d_cashier'];

        } else {
            $device_id = "";
        }
        $arrc['return_code'] = "SUCCESS";
        $arrc['result_code'] = "SUCCESS";
        $arrc['return_msg'] = "支付成功";
        $arrc['result_msg'] = "支付成功";
        $arrc['out_trade_no'] = $payinfo['orderid'];
        $arrc['trade_no'] = $payinfo['trade_no'];
        $arrc['order_no'] = $payinfo['orderno'];
        $arrc['total_fee'] = $payinfo['price'];//实付金额
        $arrc['channel'] = $payinfo['pay_fs'];//实付金额
        $arrc['merchantname'] = getmerchant($payinfo['mid']);//商户名称
        $arrc['ought_fee'] = $payinfo['yf_price'];//应付金额
        $arrc['gel_fee'] = $payinfo['zk_price'];//折扣金额
        $arrc['dis_card_zk'] = $payinfo['dis_card_zk'];        //会员卡折扣     field('dis_card_zk,vip_card_zk,gel_card_zk,hx_card')->
        $arrc['vip_card_zk'] = $payinfo['vip_card_zk'];        //等级折扣
        $arrc['gel_card_zk'] = $payinfo['gel_card_zk'];        //卡券抵扣
        $arrc['service_charge'] = $payinfo['service_charge'];        //手续费
        $arrc['end_time'] = !empty($payinfo['pay_time']) ? $payinfo['pay_time'] : "";//支付时间
        $arrc['gel_info'] = getdeduzkinfo($payinfo['hx_card'], $payinfo['gel_card_zk']);        //抵扣明细

        $arrc['device_id'] =$device_id;     //收银员
        $arrc['is_vip'] = "";        //是否会员
        $arrc['is_fans'] = "";        //是否粉丝
        $arrc['card_name'] = "";        //会员姓名
        $arrc['card_num'] = "";        //会员卡号

        //推送信息
//        $this->sendorder($orderid);

        return $arrc;


    }

    public function sendorder($orderid){
        try {
            exit();
            $url = 'http://v.wunengkeji.com/index/index/send/type/pay/orderid/' . $orderid;

            $res = $this->http_get($url);
        } catch (\Exception $e) {
            $res = array('code' => '9099', 'message' => $e->getMessage());
        }
        file_put_contents('/data2/html/osapi/kanbanlog.txt', 'res:' . json_encode($res).PHP_EOL,FILE_APPEND);
    }

    private function http_get($url)
    {
        try {
            $oCurl = curl_init();
            if (stripos($url, "https://") !== FALSE) {
                curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
                curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
            }
            curl_setopt($oCurl, CURLOPT_URL, $url);
            curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
            $sContent = curl_exec($oCurl);
            $aStatus = curl_getinfo($oCurl);
            curl_close($oCurl);
            if (intval($aStatus["http_code"]) == 200) {
                return $sContent;
            } else {
                return false;
            }
        } catch (\Exception $e) {
            $res = array('code' => '9099', 'message' => $e->getMessage());
        }
    }

    //储值充值信息
    public function get_card_balance_rec_info($orderid)
    {
        $map['a.id'] = $orderid;
        $Paylog = new Paylog();
        $CardCzgive = new CardCzgive();
        $CardUserGet = new CardUserGet();
        $CardUserRecLog = new CardUserRecLog();
        $recinfo = $CardUserRecLog->alias('a')
            ->join('wn_card_user_fee b', 'b.id=a.rec_fee_id', 'left')
            ->join('wn_card_user_bonus c', 'c.id=a.bonus_id', 'left')
            ->join('wn_card_user_fee d', 'd.id=a.give_fee_id', 'left')
            ->where($map)
            ->field('a.id,a.rec_fee_id,a.us_id,a.bonus_id,a.orderid,a.give_id,a.give_fee_id,a.create_time,ifnull(b.num,0) as rec_fee,ifnull(c.num,0) as bonus,ifnull(d.num,0) as give_fee')->find();
        $userinfo = $CardUserGet->where(['id'=>$recinfo['us_id']])->field('code,name')->find();
        $mappay['orderid'] = $recinfo['orderid'];
        $payinfo = $Paylog->where($mappay)->find();
        $giveinfo = $CardCzgive->where(['id'=>$recinfo['give_id']])->find();
        if (!empty($payinfo['cashier'])) {
            $device_id = $payinfo['cashier'];
        } elseif (!empty($payinfo['d_cashier'])) {
            $device_id = $payinfo['d_cashier'];
        } else {
            $device_id = "";
        }
        $arrc['return_code'] = "SUCCESS";
        $arrc['result_code'] = "SUCCESS";
        $arrc['return_msg'] = "支付成功";
        $arrc['result_msg'] = "支付成功";
        $arrc['out_trade_no'] = $payinfo['orderid'];
        $arrc['trade_no'] = $payinfo['trade_no'];
        $arrc['total_fee'] = $payinfo['price'];//实付金额
        $arrc['ought_fee'] = $payinfo['yf_price'];//实付金额
        $arrc['channel'] = $payinfo['pay_fs'];//支付方式
        $arrc['merchantname'] = getmerchant($payinfo['mid']);//商户
        $arrc['end_time'] = !empty($payinfo['pay_time']) ? $payinfo['pay_time'] : "";//支付时间
        $arrc['gel_info'] = getdeduzkinfo($payinfo['hx_card'], $payinfo['gel_card_zk']);        //抵扣明细
        $arrc['end_time'] = $recinfo['create_time'];
        $arrc['device_id'] =$device_id;     //收银员
        $arrc['card_name'] = $userinfo['name'];        //会员姓名
        $arrc['card_num'] = $userinfo['code'];        //会员卡号
        $arrc['add_balance'] = $recinfo['rec_fee'];      //充值金额
        $arrc['zs_balance'] = $recinfo['give_fee'];      //赠送金额
        $arrc['zs_bonus'] = $recinfo['bonus'];      //赠送积分
        $arrc['zs_cardq'] = getgivecardnew($giveinfo['zs_card_id_all'],0).getgivecard($giveinfo['zs_card_id_all'],0);      //赠送卡券
        return $arrc;
    }

    //积分充值方式
    public function get_card_bonus_rec_info($orderid){
        $map['a.id'] = $orderid;
        $CardUserGet = new CardUserGet();
        $CardUserRecLog = new CardUserRecLog();
        $recinfo = $CardUserRecLog->alias('a')
            ->join('wn_card_user_bonus b', 'b.id=a.bonus_id', 'left')
            ->where($map)
            ->field('a.action_user,a.mid,a.id,a.rec_fee_id,a.us_id,a.pay_cate,a.bonus_id,a.orderid,a.give_id,a.give_fee_id,a.create_time,b.num as bonus')->find();
        $userinfo = $CardUserGet->where(['id'=>$recinfo['us_id']])->field('code,name')->find();
        if (!empty($recinfo['action_user'])) {
            $device_id = $recinfo['action_user'];
        } elseif (!empty($recinfo['action_user'])) {
            $device_id = $recinfo['action_user'];
        } else {
            $device_id = "";
        }
        $arrc['return_code'] = "SUCCESS";
        $arrc['result_code'] = "SUCCESS";
        $arrc['return_msg'] = "支付成功";
        $arrc['result_msg'] = "支付成功";
        $arrc['channel'] = $recinfo['pay_cate'];//支付方式
        $arrc['merchantname'] = getmerchant($recinfo['mid']);//商户
        $arrc['end_time'] = $recinfo['create_time'];
        $arrc['device_id'] =$device_id;     //收银员
        $arrc['card_name'] = $userinfo['name'];        //会员姓名
        $arrc['card_num'] = $userinfo['code'];        //会员卡号
        $arrc['add_bonus'] = $recinfo['bonus'];      //充值数量
        return $arrc;
    }

    //积分核销信息
    public function get_card_bonus_con_info($orderid){
        $map['id'] = $orderid;
        $CardUserBonus = new CardUserBonus();
        $bonusinfo = $CardUserBonus->where($map)->find();
        $CardUserGet = new CardUserGet();
        $userinfo = $CardUserGet->where(['id'=>$bonusinfo['us_id']])->field('code,name')->find();
        if (!empty($bonusinfo['action_user'])) {
            $device_id = $bonusinfo['action_user'];

        } elseif (!empty($bonusinfo['action_user'])) {
            $device_id = $bonusinfo['action_user'];

        } else {
            $device_id = "";
        }
        $arrc['return_code'] = "SUCCESS";
        $arrc['result_code'] = "SUCCESS";
        $arrc['return_msg'] = "支付成功";
        $arrc['result_msg'] = "支付成功";

        $arrc['channel'] = $bonusinfo['pay_cate'];//支付方式
        $arrc['merchantname'] = getmerchant($bonusinfo['mid']);//商户
        $arrc['end_time'] = $bonusinfo['create_time'];
        $arrc['device_id'] =$device_id;     //收银员
        $arrc['card_name'] = $userinfo['name'];        //会员姓名
        $arrc['card_num'] = $userinfo['code'];        //会员卡号
        $arrc['del_bonus'] = $bonusinfo['num'];      //消费数量

        return $arrc;
    }

    //卡券核销信息
    public function get_card_con_info($code){
        $map['code'] = $code;

        $CardConsume = new CardConsume();
        $CardGeneral = new CardGeneral();
        $cardconinfo = $CardConsume->where($map)->find();
        $mapgen['card_id'] = $cardconinfo['card_id'];
        $cardinfo = $CardGeneral->where($mapgen)->field('card_type,title,least_cost,reduce_cost,discount')->find();

        if (!empty($cardconinfo['con_username'])) {
            $device_id = $cardconinfo['con_username'];

        } elseif (!empty($cardconinfo['con_username'])) {
            $device_id = $cardconinfo['con_username'];

        } else {
            $device_id = "";
        }


        $arrc['return_code'] = "SUCCESS";
        $arrc['result_code'] = "SUCCESS";
        $arrc['return_msg'] = "核销成功";
        $arrc['result_msg'] = "核销成功";
        $arrc['merchantname'] = getmerchant($cardconinfo['mid']);//商户
        $arrc['end_time'] =  $cardconinfo['create_time'];            //时间
        $arrc['card_name'] = $cardinfo['card_type'] =='CASH'?'满'.$cardinfo['least_cost'].'减'.$cardinfo['reduce_cost'].'代金券':$cardinfo['title'];    //卡券名称
        $arrc['card_name'] .= $cardinfo['card_type'] =='DISCOUNT'?'['.($cardinfo['discount']/10).'折]':'';    //卡券名称
        $arrc['card_code'] = $cardconinfo['code'];                                  //卡券号
        $arrc['card_type'] = getcardtype($cardinfo['card_type']);                   //卡券类型
        $arrc['device_id'] =$device_id;     //核销员
        return $arrc;

    }

    //退款订单信息
    public function get_order_fund($refundorderid){
        $Tklog = new Tklog();
        $Paylog = new Paylog();
        $map['tk_orderid'] = $refundorderid;
        $tkinfo = $Tklog->where($map)->find();
        $map1['orderid'] = $tkinfo['orderid'];
        $orderinfo = $Paylog->where($map1)->field('price,yf_price')->find();
        $arrc = $tkinfo;
        $arrc['return_code'] = "SUCCESS";
        $arrc['result_code'] = "SUCCESS";
        $arrc['return_msg'] = "核销成功";
        $arrc['result_msg'] = "核销成功";
        $arrc['merchantname'] = getmerchant($tkinfo['mid']);
        $arrc['out_trade_no'] = $tkinfo['orderid'];
        $arrc['refundorderno'] = $tkinfo['tk_orderid'];
        $arrc['end_time'] = date('Y-m-d H:i:s',$tkinfo['addtime']);
        $arrc['device_id'] = $tkinfo['action_user'];
        $arrc['total_fee'] = $orderinfo['price'];
        $arrc['ought_fee'] = $orderinfo['yf_price'];
        $arrc['refund_fee'] = $tkinfo['refund_fee'];
        return $arrc;
    }
    public function getFloatLength($num) {
        $count = 0;

        $temp = explode ( '.', $num );

        if (sizeof ( $temp ) > 1) {
            $decimal = end ( $temp );
            $count = strlen ( $decimal );
        }

        return $count;
    }

    //联富通调用
    //发起请求类
    public function createSign($paras, $key)
    {
        $sort_array = $this->array_sort(array_filter($paras));                //删除数组中的空值并排序
        $prestr = $this->create_linkstring($sort_array);                    //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        $prestr = $prestr . $key;                                        //把拼接后的字符串再与安全校验码直接连接起来
        $mysgin = $this->sign($prestr, $paras["sign_type"]);                //把最终的字符串签名，获得签名结果
        return $mysgin;
    }

    public function array_sort($array)
    {
        ksort($array);                                                //按照key值升序排列数组
        return $array;
    }

    /**
     * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
     * $array 需要拼接的数组
     * return 拼接完成以后的字符串
     */
    public function create_linkstring($array)
    {
        $str = "";
        while (list ($key, $val) = each($array)) {
            //键值为空的参数不参与排序，键名为key的参数不参与排序
            if ($val != null && $val != "" && $key != "key" && $key != "sign_type")
                $str .= $key . "=" . $val . "&";
        }
        $str = substr($str, 0, count($str) - 2);                        //去掉最后一个&字符
        return $str;                                                //返回参数
    }

    /**
     * 签名字符串
     * $prestr 需要签名的字符串
     * $sign_type 签名类型，也就是sec_id
     * return 签名结果
     */
    public function sign($prestr, $sign_type)
    {
        $sign = '';
        if ($sign_type == 'MD5') {
            $sign = md5($prestr);                                    //MD5加密
        } elseif ($sign_type == 'DSA') {
            //DSA 签名方法待后续开发
            die("DSA 签名方法待后续开发，请先使用MD5签名方式");
        } elseif ($sign_type == "") {
            die("sign_type为空，请设置sign_type");
        } else {
            die("暂不支持" . $sign_type . "类型的签名方式");
        }
        return strtolower($sign);                                    //返回参数并小写
    }


    public function requestAsHttpPOST($data, $service_url)
    {
        $HTTP_TIME_OUT = "20";
        $http_data = $this->array_sort(array_filter($data)); //删除数组中的空值并排序
        $post_data = http_build_query($http_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded;charset=MD5',
                'content' => $post_data,
                'timeout' => $HTTP_TIME_OUT * 1000 //超时时间,*1000将毫秒变为秒（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($service_url, false, $context);
        return $result;
    }
    //计算手续费四舍五入
    public function service_charge($mid,$price,$types){
        switch ($types) {
            case "0":
                $type = "wx_service_charge";
                break;
            case "1":
                $type = "ali_service_charge";
                break;
            case "2":
                $type = "wx_service_charge";
                break;
            case "3":
                $type = "ali_service_charge";
                break;
            case "5":
                $type = "pos_service_charge";
                break;
            case "20":
                $type = "wx_service_charge";
                break;

        }
        $Merchant=new Merchant();
        $service_charge=$Merchant->where('id',$mid)->value($type);
        $fee=number_format(($service_charge/1000)*$price,2);
        return $fee;
    }
//计算手续费四舍五入六取整
    public function service_charge_lft($mid,$price,$types){
        switch ($types) {
            case "0":
                $type = "wx_service_charge";
                break;
            case "1":
                $type = "ali_service_charge";
                break;
            case "2":
                $type = "wx_service_charge";
                break;
            case "3":
                $type = "ali_service_charge";
                break;
            case "5":
                $type = "pos_service_charge";
                break;
            case "20":
                $type = "wx_service_charge";
                break;

        }
        $Merchant=new Merchant();
        $service_charge=$Merchant->where('id',$mid)->value($type);
        $fee=service_changes(($service_charge/1000)*$price,2);
        return $fee;
    }
}